<!--
 * @Date: 2023-03-14 14:28:15
 * @LastEditTime: 2023-10-11 16:02:08
 * @FilePath: /wkw/src/tabbar/home/index.vue
 * 介绍:首页
-->

<script lang="ts" setup name="home">
import { addCache } from "@@/hooks/routeCache";
import { _require } from "@@/utils/tools";
import type CpageView from "@@/components/common/CpageView/CpageView.vue";
import useTabPageStore from "@@/store/useTabPageStore";
import { fixedDecimals, omitText } from "@@/utils/tools/format";
import useUserinfoStore from "@@/store/useUserinfoStore";
import qxd from "./components/qxd.vue";
import useSysStore from "@@/store/useSysStore";
import cloneDeep from "lodash/cloneDeep";
import { sdkFindTokenBalance } from "@@/sdk/web3Eth";
import { showDialog } from "vant";
import router from "@@/router";
import { sysLoad } from "@@/hooks/sysHooks";
import { dialogLevel } from "@@/enum/temp";
import { useInterval } from "@@/hooks/toolsHooks";
addCache("home");

const tabPageStore = useTabPageStore();
const { homeData } = storeToRefs(tabPageStore);
const userinfoStore = useUserinfoStore();
const sysStore = useSysStore();

const { t } = useI18n();

const language = computed(() => sysStore.setting.language);

const CpageViewRef = ref<InstanceType<typeof CpageView>>();

const black = ref("");
async function getBlack() {
  const contract_addr = tabPageStore.homeData?.vcc.contract_addr!;
  const address = tabPageStore.homeData?.address.black!;
  const res = await sdkFindTokenBalance(contract_addr, 18, address);
  black.value = res.data!;
}
/**获取首页数据 */
async function onRefresh(show = true) {
  if (show) CpageViewRef.value?.pullRefreshStart();
  const [homeRes] = await Promise.all([
    refreshHomeData(),
    userinfoStore.getWalletName(),
  ]);
  if (!homeRes) {
    if (show) CpageViewRef.value?.pullRefreshFail();
    return;
  }
  await getBlack();
  if (show) CpageViewRef.value?.pullRefreshSuccess();
}

sessionStorage.removeItem(dialogLevel);

useInterval(refreshHomeData, 5000);
async function refreshHomeData() {
  const res = await tabPageStore.getHomeData();
  if (res?.is_fee === 1 && !sessionStorage.getItem(dialogLevel)) {
    sessionStorage.setItem(dialogLevel, "1");
    showDialog({
      title: t("zhangHuDaiShengJi"),
      message: t("zhiFuShouXuFeiYiShenJi"),
      confirmButtonText: t("quZhiFu"),
      cancelButtonText: t("xiaCiZaiShuo"),
    }).then(() => router.push({ name: "openMatrix-levelFee" }));
  }
  return res;
}

sysLoad(() => onRefresh(false));
const invite = computed(
  () => window.location.origin + "/#/?invit=" + userinfoStore.address
);
const trees = computed(() => homeData.value?.user_info.tree);

const dots = computed(() => {
  const tree = cloneDeep(homeData.value?.user_info.tree[0]);
  const res: (string | undefined)[] = [];

  while (tree?.length) {
    const treeItem = tree.shift();
    const colors = [
      "#ee3",
      "#ee3",
      "#3CFBDE",
      "#3CFBDE",
      "#3CFBDE",
      "#3CFBDE",
      "#e33",
      "#e33",
      "#e33",
      "#e33",
      "#e33",
      "#e33",
      "#e33",
      "#e33",
    ];
    if (treeItem?.tree?.length) tree.push(...treeItem.tree);
    const color = colors[res.length] || "#f00";
    res.push(color);
  }
  for (let i = res.length; i < 14; i++) {
    res.push(undefined);
  }
  return res;
});

const levelColor: AnyObject<string | undefined> = {
  "0": undefined,
  "1": "#15EF12",
  "2": "#12F2EF",
  "3": "#F1E911",
  "4": "#F39311",
  "5": "#4075EE",
  "6": "#9910F0",
  "7": "#EA150F",
  "8": "#ea4300",
  "9": "#ff8c00",
  "10": "#e3008c",
  "11": "#5c2d91",
  "12": "#b4009e",
};
</script>

<template>
  <CpageView
    ref="CpageViewRef"
    @refresh="onRefresh(true)"
    pull-refresh
    class="home"
  >
    <div class="flex-J-SB C-M1-1">
      <div>{{ userinfoStore.walletName }}</div>
      <CcopyText :copy-text="userinfoStore.address">{{
        omitText(userinfoStore.address)
      }}</CcopyText>
    </div>
    <Bcard1 class="MT-lg">
      <div class="flex-J-SB flex-A-C">
        <Rimage
          class="flex-1"
          size="100rem"
          :src="_require('src/assets/images/mini/1.png')"
        />
        <div class="flex-A-C flex-J-C C-M1 flex-2">
          <Rimage
            height="1em"
            :src="
              _require(`src/assets/images/mini/totalRevenue__${language}.svg`)
            "
          />（<Rimage
            height="1em"
            :src="_require('src/assets/images/mini/$.svg')"
          />）
        </div>
        <div class="flex-A-C flex-J-C flex-1">
          <Rimage
            size="100rem"
            :src="_require('src/assets/images/mini/2.png')"
          />
          <div class="level-number shadow-M1">
            {{ homeData?.user_info.level }}
          </div>
        </div>
      </div>
      <div class="T-A-C T-S-xxl T-strong">
        {{ fixedDecimals(homeData?.user_info.total, 2) }}
      </div>
      <div class="flex-J-C MT-sm">
        <Bdot v-for="i in dots" :bg="i" />
      </div>
    </Bcard1>
    
    <!-- 矩阵开启 -->
    <Rbutton
      @click="$router.push({ name: 'openMatrix' })"
      block
      bg="var(--C-M1-O1)"
      class="R-0 clip-path-1 MT-md active"
      style="--clip-size: 30rem"
    >
      <Rimage
        class="flex-1"
        height="1em"
        :src="_require(`src/assets/images/mini/matrixOn__${language}.svg`)"
      />
    </Rbutton>
    <!-- 收益明细 -->
    <Rbutton
      @click="$router.push({ name: 'incomeDetail' })"
      block
      bg="var(--C-M1-O1)"
      class="R-0 clip-path-1 MT-md active"
      style="--clip-size: 30rem"
    >
      <Rimage
        class="flex-1"
        height="1em"
        :src="_require(`src/assets/images/mini/incomeDetail__${language}.svg`)"
      />
    </Rbutton>

    <Bcard1 class="MT-lg">
      <Cgrid col="2" row-gap="var(--gap-lg)">
        <Rimage
          class="shadow-M1"
          height="100rem"
          :src="_require('src/assets/images/coin/vcc.png')"
        />
        <h2>{{ fixedDecimals(homeData?.vcc.price) }}$</h2>
        <div>
          <Rimage
            class="flex-1"
            height="1em"
            :src="_require(`src/assets/images/mini/vcc.svg`)"
          />
        </div>
        <CplusMinus :value="homeData?.vcc.change" right-text="%" />
      </Cgrid>
    </Bcard1>
    <VanDivider class="MT-lg" style="color: #f8dd87">VCC</VanDivider>
    <Bcard1 v-show="homeData?.user_info.level">
      <van-swipe
        class="my-swipe"
        style="min-height: 400rem"
        indicator-color="white"
        :loop="false"
      >
        <van-swipe-item v-for="i in homeData?.user_info.level">
          <qxd
            :color="levelColor[homeData?.user_info.level.toString()!]"
            :level="trees?.at(i - 1)?.at(0)?.level || homeData?.user_info.level"
            :tree="trees?.at(i - 1)"
            class="MT-lg MB-lg"
          />
        </van-swipe-item>
      </van-swipe>
    </Bcard1>
    <!-- 社区 -->
    <Rbutton
      @click="$router.push({ name: 'community' })"
      block
      bg="var(--C-M1-O1)"
      class="R-0 clip-path-1 MT-md active"
      style="--clip-size: 30rem"
    >
      <Rimage
        height="1em"
        :src="_require(`src/assets/images/mini/community__${language}.svg`)"
      />
    </Rbutton>
    <Cgrid class="MT-md" col="1fr 1fr">
      <Bcard1>
        <!-- 储备池 -->
        <Rimage
          height="1em"
          :src="_require(`src/assets/images/mini/reservePool__${language}.svg`)"
        />
        <h2 class="MT-sm shadow-M1 T-A-C">
          {{ fixedDecimals(homeData?.reserve_pools) }}
        </h2>
        <div class="MT-sm T-A-R">30min/次</div>
      </Bcard1>
      <Bcard1>
        <!-- 黑洞 -->
        <Rimage
          height="1em"
          :src="_require(`src/assets/images/mini/blackHole__${language}.svg`)"
        />
        <h2 class="MT-sm shadow-M1 T-A-C">{{ fixedDecimals(black, 0) }}</h2>
        <div class="MT-sm T-A-R">VCC</div>
      </Bcard1>
    </Cgrid>

    <Bcard1 class="MT-md">
      <div
        class="B-img T-A-C PD-md"
        :style="{
          '--bg-img': `url(${_require('src/assets/images/display/1.png')})`,
          minHeight: '200rem',
        }"
      >
        <h3>{{ $t("yao-qing-lian-jie") }}</h3>
        <CcopyText
          v-if="Number(homeData?.user_info.level) > 0"
          class="MT-sm"
          :copy-text="invite"
          >{{ invite }}</CcopyText
        >
      </div>
    </Bcard1>
    <div class="flex MT-md gap-sm ML-xs">
      <Rimage size="80rem" :src="_require('src/assets/images/mini/3.png')" />
      <Rimage size="80rem" :src="_require('src/assets/images/mini/4.png')" />
      <Rimage size="80rem" :src="_require('src/assets/images/mini/5.png')" />
    </div>
  </CpageView>
</template>

<style lang="scss" scoped></style>
